<?php

namespace XWAM\TagLib;

/**
 * Channel 标签类
 * 用途：栏目,文章分类
 *
 * @since 1.0 <2015-10-27> SoChishun <14507247@qq.com> Added.
 * @since VER:2.0; DATE:2016-6-18; AUTHOR:SoChishun; EMAIL:14507247@qq.com; DESC:DocumentCategory和DocumentCategoryContent合并到Channel.
 * @since VER:3.0; DATE:2016-8-24; AUTHOR:SoChishun; EMAIL:14507247@qq.com; DESC:Channel重构为channel,方法统一加上get_前缀,如:content改为get_content.
 */
class channel extends TagBase {

    protected $tags = array(
        'get_list' => array('attr' => 'attrs', 'level' => 1),
        'get_tree' => array('attr' => 'attrs', 'level' => 3),
        'get_item' => array('attr' => 'attrs', 'level' => 1),
        'get_content' => array('attr' => 'attrs', 'level' => 0, 'close' => 0),
    );

    /**
     * 获取栏目内容
     * <p>用途：栏目单页内容，如关于我们、联系我们等企业信息内容</p>
     * @param type $attr
     * @param type $content
     * @return string
     * @since 1.0 <2015-11-12> SoChishun Added.
     * @since 2.0 2016-6-18 SoChishun 重构,由DocumentCategoryContent:item 改为 Channel:content
     * @example 
     * [弃用]<DocumentCategoryContent:item pk="$Think.Get.id??3" field="content">{$vo.title}</documentcategory:item>
     * [推荐]<Channel:content title="关于我们"|code="aboutus"|id="$Think.Get.id??3" length="120" />
     *      <Channel:content title="底部信息" />
     */
    public function _get_content($attr, $content) {
        $length = intval($attr['length']);
        // code取值
        $code = $attr['code'];
        // title取值
        $title = $attr['title'];
        // id取值
        $id=$this->parseIdExp($attr['id']);
        $field = empty($attr['field']) ? 'content' : $attr['field'];
        $where = array();
        if ($id) {
            $where['id'] = $id;
        } else if ($code) {
            $where['code'] = $code;
        } else if ($title) {
            $where['title'] = $title;
        }
        $cid = M('t_porg_document_category')->where($where)->getField('id');
        if (!$cid) {
            return false;
        }
        $sout = M('t_porg_document_category_content')->where(array('category_id' => $cid))->getField($field);
        if (!$sout) {
            return $sout;
        }
        $sout = html_entity_decode($sout);
        return $length ? \Org\Util\String::msubstr(strip_tags($sout), 0, $length) : $sout;
    }

    /**
     * foreach标签解析 循环输出数据集
     * @access public
     * @param array $attr 标签属性
     * @param string $content  标签内容
     * @return string|void
     * @example path description
     * @since 1.0 <2015-10-27> SoChishun Added.
     * @example 
     * <DocumentCategory:list where="pid=2 and status=1" order="sort, id">
     *      <li><a href="{:U('AboutUs/index','id='.$vo['id'])}">{$vo.title}</a></li>
     * </DocumentCategory:list>
     * <Channel:list code="aboutus">
     * <li><a href="{:U('Aboutus/'.$vo['code'])}">{$vo.title}</a></li>
     * </Channel:list>
     */
    public function _get_list($attr, $content) {
        $options = $this->parseSQLOption($attr);
        if (!empty($attr['code'])) {
            $pid = M('t_porg_document_category')->where(array('code' => $attr['code']))->getField('id');
            if (!$pid) {
                return false;
            }
            $options['where']['pid'] = $pid;
        }
        $options = array_merge($options, array('sort' => 'sort, id'));
        $name = '$' . (empty($attr['name']) ? 'res_list' : $attr['name']);
        $item = empty($attr['item']) ? 'vo' : $attr['item'];
        $key = !empty($attr['key']) ? $attr['key'] : 'key';
        $parseStr = '<?php ' . $name . '=M(\'t_porg_document_category\')->select(' . var_export($options, true) . '); ?>';
        $parseStr .= '<?php if(is_array(' . $name . ')): foreach(' . $name . ' as $' . $key . '=>$' . $item . '): ?>';
        $parseStr .= $this->tpl->parse($content);
        $parseStr .= '<?php endforeach; endif; ?>';
        return $parseStr;
    }

    /**
     * foreach标签解析 循环输出数据集
     * @access public
     * @param array $attr 标签属性
     * @param string $content  标签内容
     * @return string|void
     * @example path description
     * @since 1.0 <2015-10-27> SoChishun Added.
     * @example 
     * 
      <Channel:tree where='{"pid":36,"status":1}' order="sort,id desc" field="id, title, type_id">
      <li>
      <if condition="1 eq $vo['type_id']">
      <a href="{:U('Services/services_info','id='.$vo['id'])}">{$vo.title}</a>
      <else/>
      <a href="{:U('Services/index','id='.$vo['id'])}">{$vo.title}</a>
      </if>
      </li>
      </Channel:tree>
     */
    public function _get_tree($attr, $content) {
        $options = $this->parseSQLOption($attr);
        // where内容只能是json_encode()处理过的字符串,如where='{"pid":20}'
        if (!is_array($options['where'])) {
            throw new Exception('[TREE]的where条件格式无效!');
        }
        $name = '$' . (empty($attr['name']) ? 'res_tree' : $attr['name']);
        $item = empty($attr['item']) ? 'vo' : $attr['item'];
        $key = !empty($attr['key']) ? $attr['key'] : 'key';
        $parseStr = '<?php ' . $name . '=D(\'XWAM/DocumentCategory\')->select_tree(' . var_export($options, true) . '); ?>';
        $parseStr .= '<?php if(is_array(' . $name . ')): foreach(' . $name . ' as $' . $key . '=>$' . $item . '): ?>';
        $parseStr .= $this->tpl->parse($content);
        $parseStr .= '<?php endforeach; endif; ?>';
        return $parseStr;
    }

    /**
     * 获取字段值
     * @param type $attr
     * @param type $content
     * @return string
     * @since 1.0 <2015-11-12> SoChishun Added.
     * @example <DocumentCategory:item pk="$Think.Get.id??3" field="title" extract="true">{$vo.title}</DocumentCategory:item>{title}
     */
    function _get_item($attr, $content) {
        $pk = $attr['pk'];
        if (strpos($pk, '??')) {
            $apk = explode('??', $pk);
            $pk = $apk[0];
            if (false !== strpos($pk, '$Think')) {
                $pk = $this->parseThinkVar($pk);
            }
            $pk = '(isset(' . $pk . ') ? ' . $pk . ' : ' . $apk[1] . ')';
        } else {
            if (false !== strpos($pk, '$Think')) {
                $pk = $this->parseThinkVar($pk);
            }
        }
        $options = array('limit' => 1);
        if (!empty($attr['field'])) {
            $options['field'] = $attr['field'];
        }
        $options['cache'] = empty($attr['cache']) ? 5 : $attr['cache'];
        if ($pk) {
            $options['where'] = array('id' => '{#id}');
        }
        $soptions = '';
        if ($options) {
            $soptions = var_export($options, true);
            if ($pk) {
                $soptions = str_replace('\'{#id}\'', $pk, $soptions);
            }
        }
        $name = '$' . (empty($attr['name']) ? 'res_item' : $attr['name']);
        $item = empty($attr['item']) ? 'vo' : $attr['item'];
        $key = !empty($attr['key']) ? $attr['key'] : 'key';
        $extract = !empty($attr['extract']);
        $parseStr = '<?php ' . $name . ' = M(\'t_porg_document_category\')->select(' . $soptions . '); ?>';
        $parseStr .= '<?php if(is_array(' . $name . ')): foreach(' . $name . ' as $' . $key . '=>$' . $item . '): ?>';
        $parseStr .= $this->tpl->parse($content);
        $parseStr .= '<?php endforeach; endif; ?>';
        if ($extract) {
            $parseStr .= '<?php if(is_array(' . $name . ')): extract(' . $name . '[0]); endif; ?>';
        }

        if (!empty($parseStr)) {
            return $parseStr;
        }
        return;
    }

}
